<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import interact from 'interactjs'

// 声明控制单双页的响应式变量
const doublePage = ref(true)
const leftPageIndex = ref(1)
const rightPageIndex = ref(2)
const host = ref('http://192.168.0.112/stella-ort')
const currentBook = ref({})
const leftPage = ref({})
const rightPage = ref({})

const bookList = ref([
  {
    stage: 1,
    bookName: 'a good trick',
    bookPathName: '/images/stage-01/AGoodTrick',
    pages: [1, 2, 3, 4, 5, 6, 7, 8, 9],
    covers: {
      1: [{
        x: 137,
        y: 34,
        width: 200,
        height: 50
      }], 2: [{
        x: 570,
        y: 498,
        width: 118,
        height: 40
      }]
    }
  },
  {
    stage: 1,
    bookName: 'chip\'s robot',
    bookPathName: '/images/stage-01/Chip\'sRobot',
    pages: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
  },
  {
    stage: 1,
    bookName: 'go on mum',
    bookPathName: '/images/stage-01/GoOnMum',
    pages: [0,2, 3, 4, 5, 6, 7, 8, 9, 11]
  }
])

// 下一页按钮点击事件
function nextPage() {
  const pages = currentBook.value.pages || []
  const currentIndex = leftPageIndex.value

  if (doublePage.value) {
    // 双页模式：索引增加2
    if (currentIndex !== -1 && currentIndex + 1 < pages.length) {
      const nextIndex = currentIndex + 2
      if (nextIndex < pages.length-1) {
        leftPageIndex.value = nextIndex;
      } else if (nextIndex === pages.length-1) {
        // 到达最后一页且总页数为奇数的情况
        leftPageIndex.value = pages.length - 1;
        doublePage.value = false
      }
    }
  } else {
    // 单页模式：索引增加1
    if (currentIndex !== -1 && currentIndex + 1 < pages.length) {
      leftPageIndex.value = currentIndex + 1;
      // 检查是否还有下一页，如果有且当前是单页模式，可以考虑切换回双页
      if (currentIndex + 1 < pages.length - 1 && !doublePage.value) {
        doublePage.value = true
      }
    }
  }
  rightPageIndex.value = leftPageIndex.value + 1

  // 更新页面图片路径
  updatePageImages()
}

// 上一页按钮点击事件
function prevPage() {
  const currentIndex = leftPageIndex.value

  if (doublePage.value) {
    // 双页模式：索引减少2
    if (currentIndex >= 2) {
      leftPageIndex.value = currentIndex - 2
    }
  } else {
    // 单页模式：索引减少1
    if (currentIndex > 0) {
      leftPageIndex.value = currentIndex - 2
      doublePage.value = true
    }
  }

  rightPageIndex.value = leftPageIndex.value + 1

  // 更新页面图片路径
  updatePageImages()
}

// 更新页面图片路径的辅助函数
function updatePageImages() {
  const pages = currentBook.value.pages || []
  const currentIndex = leftPageIndex.value
  const leftPageNum=pages[currentIndex]
  const bookPath = currentBook.value.path

  if (bookPath) {
    leftPage.value = `${bookPath}/${leftPageNum.toString().padStart(3, '0')}.png`
    if (doublePage.value && currentIndex + 1 < pages.length) {
      const rightPageNumber = pages[currentIndex + 1]
      rightPage.value = `${bookPath}/${rightPageNumber.toString().padStart(3, '0')}.png`
    }
  }
}

function openBook(item, index) {
  console.log('open book:', host.value,item.bookPathName)
  currentBook.value = {
    ...item,
    index: index,
    path: `${host.value}${item.bookPathName}`
  }
  // 重置页码
  leftPageIndex.value = 0
  doublePage.value = true

  // 使用统一的更新页面图片函数
  updatePageImages()
}


// 添加键盘事件处理函数
function handleKeyDown(event) {
  // 阻止默认行为（如页面滚动）
  switch (event.key) {
    case 'ArrowUp':
    case 'ArrowLeft':
      event.preventDefault()
      prevPage()
      break
    case 'ArrowDown':
    case 'ArrowRight':
      event.preventDefault()
      nextPage()
      break
  }
}

onMounted(() => {
  openBook(bookList.value[0], 0)
  // host.value = window.location.origin
  console.log('host:', host.value)
  // initDrag('.draggable')
  // 使 .draggable 元素可拖拽
  interact('.draggable')
    .draggable({
      inertia: true, // 惯性效果
      autoScroll: true,
      // 拖拽过程中
      onmove: (event) => {
        const target = event.target
        const x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
        const y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy

        // 更新元素位置
        target.style.transform = `translate(${x}px, ${y}px)`

        // 保存位置到 data 属性
        target.setAttribute('data-x', x)
        target.setAttribute('data-y', y)
      },
      // 拖拽结束时可记录位置（可用于保存遮罩坐标）
      onend: (event) => {
        const target = event.target
        const x = target.getAttribute('data-x')
        const y = target.getAttribute('data-y')
        console.log('拖拽结束，位置：', { x, y })
      }
    })

  // 如果你还需要缩放功能（用于调整遮罩大小）
  interact('.draggable')
    .resizable({
      edges: { left: true, right: true, bottom: true, top: true },
      preserveAspectRatio: false,
      invert: 'negate' // 允许缩小到 0
    })
    .on('resizemove', function(event) {
      const target = event.target
      const x = (parseFloat(target.getAttribute('data-x')) || 0)
      const y = (parseFloat(target.getAttribute('data-y')) || 0)

      // 更新宽高
      target.style.width = event.rect.width + 'px'
      target.style.height = event.rect.height + 'px'

      // 更新位置（因为缩放可能改变左上角）
      target.style.transform = `translate(${x + event.deltaRect.left}px, ${y + event.deltaRect.top}px)`

      // 保存新位置
      target.setAttribute('data-x', x + event.deltaRect.left)
      target.setAttribute('data-y', y + event.deltaRect.top)
    })

  window.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
</script>

<template>
  <div class="book-list">
    <ul>
      <li v-for="(item,index) in bookList" @click="openBook(item,index)"> {{ item.bookName }}</li>
    </ul>

  </div>
  <div class="container book-container">
    <!-- 模拟绘本图片背景 -->
    <div class="book-page">
      <img alt="绘本图片" style=" width: 100%;"
           :src="leftPage" />
    </div>
    <div class="book-page" v-if="doublePage">
      <img alt="绘本图片" style=" width: 100%;"
           :src="rightPage" />
    </div>

    <!-- 可拖拽 + 缩放的遮罩-第一页 -->
    <div
      v-for="(item, index) in (currentBook.covers && currentBook.covers[currentBook.pages[leftPageIndex]] || [])"
      :key="index"
      class="draggable draggable-ele"
      :data-x="item.x"
      :data-y="item.y"
      :style="{
      width: item.width + 'px',
      height: item.height + 'px',
      transform: `translate(${item.x}px, ${item.y}px)`
    }">
    </div>
    <!-- 第二页遮罩元素 -->
    <div v-if="doublePage"
         v-for="(item, index) in (currentBook.covers && currentBook.covers[currentBook.pages[rightPageIndex]] || [])"
         :key="index"
         class="draggable draggable-ele"
         :data-x="item.x"
         :data-y="item.y"
         :style="{
      width: item.width + 'px',
      height: item.height + 'px',
      transform: `translate(${item.x}px, ${item.y}px)`
    }">
    </div>
  </div>

  <div class="button-container">
    <div>
      <span>第{{leftPageIndex}},{{rightPageIndex}}页</span>
      <span>共{{currentBook.pages && currentBook.pages.length-1}}页</span>
    </div>
    <input type="button" value="◀️ prev" id="prevBtn" class="page-btn" @click="prevPage">
    <input type="button" value="next ▶️" id="nextBtn" class="page-btn" @click="nextPage">
  </div>
</template>

<style>
/* 可选：让整个页面更美观 */
body {
  margin: 0;
  font-family: Arial, sans-serif;
  background: #f5f5f5;
}

.button-container {
  margin: 0 auto;
  text-align: center;
}

.page-btn {
  width: 60px;
  height: 30px;
  margin: 5px;
}

.book-container {
  position: relative;
  width: 840px;
  border: 1px solid #ccc;
  margin: 0 auto;
  overflow: hidden;
  text-align: center
}

.book-page {
  display: inline-block;
  width: 420px;
  margin: 0 auto;
}

.book-list {
  position: fixed;
  top: 10px;
  left: 100px;
  line-height: 25px;
  cursor: pointer;
}

.draggable-ele {
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(255, 255, 255, 1.0);
  border: 1px dashed yellow;
  cursor: move;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
}
</style>